<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片拾色</title>
    <style>
        #rgbValue1,
        #rgbValue2 {
            padding: 20px;
            margin: 0 10px;
        }
        p {
            margin: 30px 0;
        }
</style>
</head>
<body>
    <h1>图片拾色</h1>
    <input type="file" accept="Image" id="input">
    <p>
        <canvas id="canvas"></canvas>
    </p>
    <p><span id="rgbValue1"></span><span id="rgbValue"></span></p>
    <p><span id="rgbValue2"></span><span id="rgbValue3"></span></p>
    <p id="rgbValue2"></p>
</body>
<script>
    const img = new Image();
    const file = document.getElementById('input')
    const rgbValue1 = document.getElementById('rgbValue1')
    const rgbValue = document.getElementById('rgbValue')
    const rgbValue2 = document.getElementById('rgbValue2')
    const rgbValue3 = document.getElementById('rgbValue3')
    let url
    file.addEventListener('change', e => {
        url = URL.createObjectURL(e.target.files[0])
    console.log(url);
    // img.crossOrigin = "anonymous";
    img.width = 500
    img.height =500
    img.src = url;
    console.log(img);
    const canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = img.width
    canvas.height = img.height

    img.onload = function () {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    };
    const hoveredColor = document.getElementById("hovered-color");
    const selectedColor = document.getElementById("selected-color");

    function pick(event, destination) {
        let x = event.layerX;
        let y = event.layerY;
        let pixel = ctx.getImageData(x, y, 1, 1);
        let data = pixel.data;

        const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`;
        // console.log(rgba);
        return rgba;
    }

    canvas.addEventListener("mousemove", function (event) {
        rgbValue.innerHTML = "移动取色：" + pick(event, hoveredColor);
        rgbValue1.style.background = pick(event, hoveredColor);
        // rgbValue1.style.padding = '20px';
    });
    canvas.addEventListener("click", function (event) {
        rgbValue3.innerHTML = "点击取色：" + pick(event, selectedColor);
        rgbValue2.style.background = pick(event, hoveredColor);

    });

    })
</script>
</html>